package club.janna.rpcdemo.client.discover;

import club.janna.rpcdemo.domain.ServiceInfo;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public abstract class AbstractServiceDiscover implements ServiceDiscover {
    protected Map<String, List<ServiceInfo>> serviceMap = new HashMap<>();

    @Override
    public ServiceInfo getServiceInfo(String serviceName) {
        List<ServiceInfo> serviceInfoList = serviceMap.get(serviceName);
        if(CollectionUtils.isEmpty(serviceInfoList))
            return null;
        int size;
        return (size = serviceInfoList.size()) == 1 ? serviceInfoList.get(0) : serviceInfoList.get(new Random().nextInt(size));
    }
}
